class WebSocketClient {
    constructor() {
        this.socket = null;
        this.isConnected = false;
        this.initializeElements();
        this.bindEvents();
    }
    
    initializeElements() {
        this.statusEl = document.getElementById('status');
        this.messagesEl = document.getElementById('messages');
        this.messageInput = document.getElementById('messageInput');
        this.sendBtn = document.getElementById('sendBtn');
        this.targetIdInput = document.getElementById('targetIdInput');
        this.privateMessageInput = document.getElementById('privateMessageInput');
        this.sendPrivateBtn = document.getElementById('sendPrivateBtn');
        this.connectBtn = document.getElementById('connectBtn');
        this.disconnectBtn = document.getElementById('disconnectBtn');
        this.pingBtn = document.getElementById('pingBtn');
        this.clearBtn = document.getElementById('clearBtn');
    }
    
    bindEvents() {
        this.connectBtn.addEventListener('click', () => this.connect());
        this.disconnectBtn.addEventListener('click', () => this.disconnect());
        this.sendBtn.addEventListener('click', () => this.sendMessage());
        this.sendPrivateBtn.addEventListener('click', () => this.sendPrivateMessage());
        this.pingBtn.addEventListener('click', () => this.sendPing());
        this.clearBtn.addEventListener('click', () => this.clearMessages());
        
        // 回车发送消息
        this.messageInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                this.sendMessage();
            }
        });
        
        this.privateMessageInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                this.sendPrivateMessage();
            }
        });
    }
    
    connect() {
        if (this.isConnected) return;

        //使用 socket.io 库建立与服务器的 WebSocket 连接
        this.socket = io('http://192.168.137.1:3001');

        //下面的监听事件处理函数，是由监听后端emit发送过来的消息处理函数
        
        // 连接成功
        this.socket.on('connect', () => {
            this.isConnected = true;
            this.updateStatus('已连接', true);
            this.enableControls(true);
            this.addMessage('system', `已连接到服务器，您的ID: ${this.socket.id}`);
        });
        
        // 连接断开
        this.socket.on('disconnect', () => {
            this.isConnected = false;
            this.updateStatus('连接断开', false);
            this.enableControls(false);
            this.addMessage('system', '与服务器的连接已断开');
        });
        
        // 欢迎消息
        this.socket.on('welcome', (data) => {
            this.addMessage('welcome', `${data.message} (${data.timestamp})`);
        });
        
        // 广播消息
        this.socket.on('server_broadcast', (data) => {
            this.addMessage('broadcast', `[${data.timestamp}] ${data.user}: ${data.message}`);
        });
        
        // 私聊消息
        this.socket.on('private_message_received', (data) => {
            this.addMessage('private', `[私聊][${data.timestamp}] ${data.from}: ${data.message}`);
        });
        
        // 用户离开
        this.socket.on('user_left', (data) => {
            this.addMessage('system', `[${data.timestamp}] 用户 ${data.userId} 已离开`);
        });
        
        // 心跳响应
        this.socket.on('pong', (data) => {
            this.addMessage('system', `心跳响应: ${data.timestamp}`);
        });
        
        // 连接错误
        this.socket.on('connect_error', (error) => {
            this.addMessage('system', `连接错误: ${error.message}`);
        });
    }
    
    disconnect() {  //  断开连接
        if (this.socket && this.isConnected) {
            this.socket.disconnect();
        }
    }
    
    sendMessage() {  //  发送消息
        const message = this.messageInput.value.trim();  //获取消息内容
        if (!message || !this.isConnected) return;
        
        this.socket.emit('client_message', {
            message: message
        });
        
        this.messageInput.value = '';
    }
    
    sendPrivateMessage() {
        const targetId = this.targetIdInput.value.trim();
        const message = this.privateMessageInput.value.trim();
        
        if (!targetId || !message || !this.isConnected) {
            alert('请输入目标用户ID和消息内容');
            return;
        }
        
        this.socket.emit('private_message', {
            targetId: targetId,
            message: message
        });
        
        this.addMessage('private', `[私聊发送给 ${targetId}]: ${message}`);
        this.privateMessageInput.value = '';
    }
    
    sendPing() {
        if (!this.isConnected) return;
        
        this.socket.emit('ping');
        this.addMessage('system', '发送心跳包...');
    }
    
    updateStatus(text, connected) {
        this.statusEl.textContent = `状态: ${text}`;
        this.statusEl.className = `status ${connected ? 'connected' : 'disconnected'}`;
    }
    
    enableControls(enabled) {
        this.messageInput.disabled = !enabled;
        this.sendBtn.disabled = !enabled;
        this.targetIdInput.disabled = !enabled;
        this.privateMessageInput.disabled = !enabled;
        this.sendPrivateBtn.disabled = !enabled;
        this.pingBtn.disabled = !enabled;
        this.connectBtn.disabled = enabled;
        this.disconnectBtn.disabled = !enabled;
    }
    
    addMessage(type, content) {
        const messageEl = document.createElement('div');
        messageEl.className = `message ${type}`;
        messageEl.textContent = content;
        
        this.messagesEl.appendChild(messageEl);
        this.messagesEl.scrollTop = this.messagesEl.scrollHeight;
    }
    
    clearMessages() {
        this.messagesEl.innerHTML = '';
    }
}

// 初始化客户端
const client = new WebSocketClient();